package cn.com.qingz.modules.system.controller;

import java.io.*;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;

import cn.com.qingz.core.constantes.SystemConstantes;
import cn.com.qingz.core.exception.DicmfException;
import cn.com.qingz.core.model.DefaultResp;
import cn.com.qingz.core.utils.MD5;
import cn.com.qingz.core.utils.QiNiuStorage;
import cn.com.qingz.core.utils.QiNiuTool;

@Controller
@RequestMapping("file/*")
public class FileController {

    // 上传图片 返回文件名

    @RequestMapping("uploadImage")
    public void uploadPicture(HttpServletRequest request, HttpServletResponse response, MultipartHttpServletRequest multipartHttpServletRequest) throws IOException {
        //		DefaultResp<String> res = new DefaultResp<String>();
        //		MultipartFile picture = multipartHttpServletRequest.getFile("files"); //上传的图片
        //    	if( picture==null ){
        //    		throw new DicmfException(SystemConstantes.ERROR, "上传图片不能为空");
        //    	}
        //
        //    	String extensionName = getExtensionName(picture.getOriginalFilename());
        //    	if("jpg".equals(extensionName) ||  "jpeg".equals(extensionName ) || "png".equals(extensionName)){
        //    		String pictureMd5 = MD5.GetMD5Code(new Date().getTime() + picture.getName());
        //    		Map<String, String> sysparam = (Map<String, String>) request.getSession().getServletContext().getAttribute(SystemConstantes.SYS_PARAM);
        //        	String diskURI = sysparam.get(SystemConstantes.IMAGE_UPLOAD_URL);
        //            InputStream in = picture.getInputStream();
        //            OutputStream out =  new FileOutputStream(new File(diskURI+ pictureMd5 + "."+ extensionName)) ;
        //        	try {
        //             	IOUtils.copy(in, out);
        //            } finally {
        //                IOUtils.closeQuietly(in);
        //                IOUtils.closeQuietly(out);
        //            }
        //        	res.setData(pictureMd5 + "."+ extensionName);
        //    	}else{
        //    		throw new DicmfException(SystemConstantes.ERROR, "文件格式必须为 jpg|jpeg|png");
        //    	}
        ////    	return res;
        //    	response.getOutputStream().write(JSON.toJSONString(res).getBytes());
        //    	response.getOutputStream().flush();
        //    	response.getOutputStream().close();
        qiniuFileUpload(request, response, multipartHttpServletRequest);
    }

    /**
     * 上传任意文件
     * @param request
     * @param response
     * @param multipartHttpServletRequest
     * @throws IOException
     */
    @RequestMapping("uploadAnyFile")
    @ResponseBody
    public DefaultResp<String> uploadAnyFile(HttpServletRequest request, HttpServletResponse response, MultipartHttpServletRequest multipartHttpServletRequest) throws IOException {
        DefaultResp<String> res = new DefaultResp<String>();
        MultipartFile file = multipartHttpServletRequest.getFile("files"); //上传的图片
        if (file == null) {
            throw new DicmfException(SystemConstantes.ERROR, "上传文件不能为空");
        }

        String pictureMd5 = MD5.GetMD5Code(new Date().getTime() + file.getName());
        String extensionName = getExtensionName(file.getOriginalFilename());
        Map<String, String> sysparam = (Map<String, String>) request.getSession().getServletContext().getAttribute(SystemConstantes.SYS_PARAM);
        String diskURI = sysparam.get(SystemConstantes.FILE_UPLOAD_URL);
        InputStream in = file.getInputStream();
        OutputStream out = new FileOutputStream(new File(diskURI + pictureMd5 + "." + extensionName));
        try {
            IOUtils.copy(in, out);
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
        res.setData("http://download.lipe-home.com/" + pictureMd5 + "." + extensionName);
        return res;
        //    	response.getOutputStream().write(JSON.toJSONString(res).getBytes());
        //    	response.getOutputStream().flush();
        //    	response.getOutputStream().close();
    }

    /**
     * 七牛云存储 图片上传
     * @param request
     * @param response
     * @param multipartHttpServletRequest
     * @throws IOException
     */
    @RequestMapping("qiniuFileUpload")
    public void qiniuFileUpload(HttpServletRequest request, HttpServletResponse response, MultipartHttpServletRequest multipartHttpServletRequest) throws IOException {
        DefaultResp<String> res = new DefaultResp<String>();
        List<MultipartFile> pictures = multipartHttpServletRequest.getFiles("files"); //上传的图片
        if (pictures == null) {
            throw new DicmfException(SystemConstantes.ERROR, "上传图片不能为空");
        }
        StringBuffer sb = new StringBuffer();
        for (MultipartFile picture : pictures) {
            String extensionName = getExtensionName(picture.getOriginalFilename());
            if ("jpg".equalsIgnoreCase(extensionName) || "jpeg".equalsIgnoreCase(extensionName) || "png".equalsIgnoreCase(extensionName)) {
                InputStream in = picture.getInputStream();
                QiNiuStorage storage = new QiNiuStorage();
                QiNiuTool.Config conf = new QiNiuTool.Config();
                conf.setAccessKey("lfECzeWMKQp0wsroqHTNdlXZ824aIcIAsflF7fdk");
                conf.setBucket("codeblue-images");
                conf.setExpires(200000);
                conf.setSecretKey("9MiEFdsBOSzo0cyZz8mrnK5r7PgyaBD9oOUcCSTL");
                conf.setHost("7xl6wk.com1.z0.glb.clouddn.com ");
                storage.setConfig(conf);
                String resstring = storage.store(in);
                //				res.setData(resstring);
                sb.append(resstring);
                sb.append(",");
            } else {
                throw new DicmfException(SystemConstantes.ERROR, "文件格式必须为 jpg|jpeg|png");
            }
        }
        sb.deleteCharAt(sb.length() - 1);
        res.setData(sb.toString());
        //    	return res;
        response.getOutputStream().write(JSON.toJSONString(res).getBytes());
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }

    @RequestMapping("delImage")
    @ResponseBody
    public DefaultResp<String> delImage(String pictureName, HttpServletRequest request) throws IOException {
        DefaultResp<String> res = new DefaultResp<String>();
        Map<String, String> sysparam = (Map<String, String>) request.getSession().getServletContext().getAttribute(SystemConstantes.SYS_PARAM);
        String diskURI = sysparam.get(SystemConstantes.IMAGE_UPLOAD_URL);
        FileUtils.deleteQuietly(new File(diskURI + pictureName));
        return res;
    }

    /*
     * Java文件操作 获取文件扩展名
     */
    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }

    /*
     * Java文件操作 获取不带扩展名的文件名
     */
    public static String getFileNameNoEx(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length()))) {
                return filename.substring(0, dot);
            }
        }
        return filename;
    }
}